import qs from 'qs'
import { ref, reactive, nextTick, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from 'vue-router';
import { FXQ } from "@/utils/public/FXQ"
import {
  EnterpriseinformationSelectEnterpriseCreditReport,
  EnterGetAllByPagedAndSort,
  GetAllEnterprisereportInfo,
  GetEnterpriseCreditReport,
  GetEnterpriseentrustByRId,
  SelectPersonalReport,
  GetMoudleKeyValue
} from "@/api/stu/DataScene"

export function useFirmCredit() {
  // 分页
  const isSeal = ref<boolean>(false)
  const route = useRoute();
  const RepotFroms = ref();
  const poweratData = ref();
  const powerattorney_ = ref();
  const dataList = ref<any>([]);
  const dataList2 = ref<any>([]);
  const ShowReport = ref<string>("");
  const loading = ref<boolean>(true);
  const loading2 = ref<boolean>(true);
  const btnloading = ref<boolean>(false);
  const TabsActiveName = ref<string>("1");
  const RepotVisible = ref<boolean>(false);
  const CreditPowerVisible = ref<boolean>(false);
  const CreditReportVisible = ref<boolean>(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "企业名称",
      prop: "enterpriseName",
      minWidth: 100,
    },
    {
      label: "注册地址",
      prop: "registerAddress",
      minWidth: 100,
    },
    {
      label: "登记注册类型",
      prop: "registerType",
      minWidth: 110,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.registerType ? "warning" : "primary"}>
          {
            row.registerType ? "外商投资企业" : "内资企业"
          }
        </el-tag>
      )
    },
    {
      label: "登记注册号",
      prop: "registerNo",
      minWidth: 100
    },
    {
      label: "登记注册日期",
      prop: "registerDate",
      minWidth: 200,
    },

    {
      label: "有效截至日期",
      prop: "endDate",
      minWidth: 150,
    },
    {
      label: "组织机构代码",
      prop: "organizationCode",
      minWidth: 150
    },
    {
      label: "中征码",
      prop: "strikeCode",
      minWidth: 100
    },
    {
      label: "国税登记号",
      prop: "nationalTaxNo",
      minWidth: 200
    },
    {
      label: "地税登记号",
      prop: "landTaxNo",
      minWidth: 200
    },
    {
      label: "法定代表人",
      prop: "corporateName",
      minWidth: 150
    },
  ];
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "企业名称",
      prop: "eName",
      minWidth: 200
    },
    {
      label: "报告编号",
      prop: "reportNo",
      minWidth: 300
    },
    {
      label: "查询申请人类型",
      prop: "applicantType",
      minWidth: 300,
      cellRenderer: ({ row }) => (
        <el-tag>
          {
            row.applicantType == '1' ? "企业法定代表人" : "企业法定代表人授权的代理人"
          }
        </el-tag>
      )
    },
    {
      label: "查询时间",
      prop: "queryDate",
      minWidth: 300
    },
    {
      label: "操作",
      fixed: "right",
      width: 255,
      slot: "operation"
    }
  ];
  const regex = /^[\u4e00-\u9fa5]{2,4}$/;// 校验2-4个字中文
  const regex2 = /^[\u4e00-\u9fa5]{2,18}$/;// 校验2-4个字中文
  const regPhone = /^1[3456789]\d{9}$/;
  const regID = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  // 校验申请表单
  const rules = {
    FirmName: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          console.log("regex2.test(RepotFrom.FirmName)", regex2.test(RepotFrom.FirmName))
          if (!regex2.test(RepotFrom.FirmName)) {
            return callback(new Error('请输2-18的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    NameApplicant: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!regex.test(RepotFrom.NameApplicant)) {
            return callback(new Error('请输2-4的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    OrganizationCode: [{
      required: true,
      message: "请输入9位数字机构代码"
    }],
    ApplicantPhone: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: (rule: any, value: any, callback: () => void) => {
          if (!regPhone.test(RepotFrom.ApplicantPhone)) {
            return callback(new Error('请输正确的手机号'))
          } else {
            // 校验通过
            return callback()
          }
        },
      }
    ],
    ApplicantId: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: (rule: any, value: any, callback: () => void) => {
          if (!regID.test(RepotFrom.ApplicantId)) {
            return callback(new Error('请输入正确的证件码'))
          } else {
            // 校验通过
            return callback()
          }
        },
      }
    ],
    SignApplicant: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!regex.test(RepotFrom.SignApplicant)) {
            return callback(new Error('请输2-4的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    QueryApplicantType: [
      {
        required: true,
        message: '请选择查询申请人类型',
        trigger: ["blur", "change"],
      }
    ],
    QueryTime: [
      {
        type: 'date',
        required: true,
        message: '请选择日期',
        trigger: ["blur", "change"],
      }
    ],
    ApplicationDate: [
      {
        type: 'date',
        required: true,
        message: '请选择申请日期',
        trigger: ["blur", "change"],
      }
    ]
  }
  const RepotFrom2 = reactive({
    enterpriseName: "",//企业名称
    organizationCodes: "",//组织机构代码
    queryDate: "",//授权日期
    DateIssue: "",// 签发日期
    applyName: "",// 代理人名称
    LegalName: "",//法定代表人签字
    applyCertificateNo: "",//证件号码
    applyPhone: "",// 代理人联系方式
    applySign: "",//代理人签字
    signDate: "" // 代理日期
  })

  const RepotFrom = reactive({
    FirmName: "", // 企业名称
    OrganizationCode: "", //组织机构代码
    QueryApplicantType: 1, //查询申请人类型
    NameApplicant: "", // 申请人名称
    ApplicantId: "", // 申请人证件号码
    ApplicantPhone: "", // 有效电话
    QueryTime: "", //查询时间
    SignApplicant: "", // 申请人签字
    ApplicationDate: "" // 申请日期
  })
  /* 模块一 */
  // 获取征信报告
  async function GetRepot() {
    const data = qs.stringify({ submoduleName: "企业征信中心" })
    const res = await GetMoudleKeyValue(data)
    // console.log("获取征信报告", res)
    RepotVisible.value = true;
  }

  // 关闭表单并初始化
  function CloseApplication(row: FormInstance | undefined) {
    TabsActiveName.value = "1"
    RepotVisible.value = false;
    row.resetFields();
  }

  // 提交申请表单
  async function SubmitApplication(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      // 学生答案
      try {
        if (RepotFrom.QueryApplicantType === 2) {
          const state = powerattorney_.value.seal();
          if (!state) return
          if (!isSeal.value) {
            ElMessage.warning("尚未盖章");
            return;
          }
          var {
            DateIssue,
            LegalName,
            applyCertificateNo,
            applyName,
            applySign,
            enterpriseName,
            organizationCodes,
            queryDate,
            signDate
          } = powerattorney_.value.RepotFrom2;
        };
        const {
          QueryApplicantType,
          FirmName,
          OrganizationCode,
          QueryTime,
          ApplicationDate,
          NameApplicant,
          ApplicantId,
          ApplicantPhone,
          SignApplicant
        } = RepotFrom;
        const studentAnswer = [
          {
            "key": "B0301",
            "value": FirmName
          },
          {
            "key": "B0302",
            "value": OrganizationCode
          },
          {
            "key": "B0303",
            "value": QueryApplicantType
          },
          {
            "key": "B0101",
            "value": NameApplicant
          },
          {
            "key": "B0102",
            "value": ApplicantId
          },
          {
            "key": "B0103",
            "value": ApplicantPhone
          },
          {
            "key": "B0304",
            "value": QueryTime
          },
          {
            "key": "B0305",
            "value": enterpriseName
          },
          {
            "key": "B0306",
            "value": organizationCodes
          },
          {
            "key": "B0307",
            "value": applyName
          },
          {
            "key": "B0308",
            "value": applyCertificateNo
          },
          {
            "key": "B0309",
            "value": queryDate,
          },
          {
            "key": "B0310",
            "value": signDate
          },
          {
            "key": "B0311",
            "value": DateIssue
          }
        ];
        const StubimData = {
          type: QueryApplicantType,
          studentAnswer: JSON.stringify(studentAnswer),
          enterpriseLegalDto: {
            planId: route.query.planId,
            taskId: route.query.taskId,
            enterpriseName: FirmName,//企业名称
            organizationCode: OrganizationCode,//组织机构代码
            queryDate: QueryTime,//查询日期
            signDate: ApplicationDate,// 申请日期
            applyName: NameApplicant,//申请人名称
            applyCertificateNo: ApplicantId,//申请人证件号码
            applyPhone: ApplicantPhone,//申请人有效联系电话
            applySign: SignApplicant,//申请人签字
          },
          enterpriseLicensorDto: {
            thisCompanyName: enterpriseName,//本企业名称
            // thisCertificateType: "组织机构代码",//本企业证件类型
            thisCertificateNo: organizationCodes,//本企业证件号码
            agentName: applyName,//代理人名称
            // agentCertificateType: "身份证",//代理人证件类型
            agentCertificateNo: applyCertificateNo,//代理人证件号码
            legalPerson: LegalName,//企业法定代表人签字
            authorizeDate: queryDate,//授权有效期
            agent: applySign,//代理人签字
            agentDate: signDate,//代理人签发日期
            legalPersonDate: DateIssue// 企业法定代表人签字日期
          }
        };
        btnloading.value = true;
        const res = await GetEnterpriseCreditReport(StubimData);
        if (res.success) {
          ElMessage.success(res.msg);
          CloseApplication(row)
          btnloading.value = false;
        } else {
          ElMessage.error(res.msg);
          setTimeout(() => {
            btnloading.value = false;
          }, 1500)
        }
      } catch (error) {
        console.log(error);
      };
    })
  }

  // 盖章
  function SubmitSeal() {
    const state = powerattorney_.value.seal();
    const datas_ = powerattorney_.value.RepotFrom2;
    if (RepotFrom.QueryApplicantType === 2 && !state) {
      return
    }
    // 生成章
    const MYFXQ = FXQ.companySeal(datas_.enterpriseName, 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
    isSeal.value = true
  }

  // 查看企业征信报告
  async function CheckCreditReport(row) {
    const data = qs.stringify({
      "reportId": row.rId,
      "userId": row.userId,
      "planId": row.planId,
      "taskId": row.taskId
    })
    const respone = await EnterpriseinformationSelectEnterpriseCreditReport(data);
    if (respone.success) {
      CreditReportVisible.value = true;
      nextTick(() => {
        ShowReport.value = respone.data
      })
    } else {
      ElMessage.error(respone.msg)
    }
  }

  // 查看企业委托书
  async function CheckCreditPower(row) {
    const params = qs.stringify({ rId: row.rId })
    const res = await GetEnterpriseentrustByRId(params);
    if (res.success) {
      CreditPowerVisible.value = true;
      nextTick(() => {
        poweratData.value = res.data;
      });
    } else {
      ElMessage.warning(res.msg)
    }
  }

  // 分页
  function handleSizeChange(val) {
    GetMyDataSystem()
  }

  function handleCurrentChange(val) {
    GetMyDataSystem()
  }

  // 分页
  function handleSizeChanges(val) {
    GetreportPagedAndSort()
  }

  function handleCurrentChanges(val) {
    GetreportPagedAndSort()
  }
  /* 模块一 end*/
  ////////////////////////////////
  /* 模块二 */
  // 查看征信报告
  function ShowRepot() {

  }
  /* 模块2 end*/

  // 获取企业征信数据系统
  async function GetMyDataSystem() {
    const res = await EnterGetAllByPagedAndSort({
      planId: route.query.planId,
      taskId: route.query.taskId,
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize
    });
    if (res.success) {
      pagination.total = res.data.totalCount;
      dataList.value = res.data.items;
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false }, 1500)
    }
    // pagination.total = data.totalCount;
    // dataList.value = data.items;
  }

  // 获取企业征信数据系统
  async function GetreportPagedAndSort() {
    const data = {
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
    };
    const res = await GetAllEnterprisereportInfo(data);
    if (res.success) {
      pagination2.total = res.data.totalCount;
      dataList2.value = res.data.items;
      loading2.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading2.value = false }, 1500)
    }
    // pagination2.total = res.data.totalCount;
    // dataList2.value = res.data.items;
  }

  function HandTabClick() {

  }

  // // 获取委托书
  // async function GetEnterpriseentrustByRIds() {
  //   const data = qs.stringify({ rId: 26 })
  //   const res = await GetEnterpriseentrustByRId(data);
  //   console.log("查看委托书", res)
  // }

  onMounted(() => {
    GetMyDataSystem()
    GetreportPagedAndSort()
    // GetEnterpriseentrustByRIds()
  })

  return {
    isSeal,
    RepotFroms,
    dataList,
    dataList2,
    loading,
    loading2,
    btnloading,
    poweratData,
    powerattorney_,
    RepotVisible,
    TabsActiveName,
    CreditPowerVisible,
    CreditReportVisible,
    pagination,
    pagination2,
    ShowReport,
    columns,
    columns2,
    rules,
    RepotFrom,
    RepotFrom2,
    GetRepot,
    SubmitSeal,
    GetreportPagedAndSort,
    CheckCreditReport,
    handleSizeChange,
    CheckCreditPower,
    handleCurrentChange,
    handleSizeChanges,
    handleCurrentChanges,
    CloseApplication,
    SubmitApplication,
    ShowRepot
  }
}
